import { login, getUserInfo } from '@/api/user'
import {
  getToken,
  setToken,
  removeToken
} from '@/utils/token'

const state = {
  token: getToken(),
  userInfo: null,
  enterpriseInfo: null,
  permissionList: []
}

const getters = {
  account: state => state.userInfo ? state.userInfo.account : '',
  telephone: state => state.userInfo ? state.userInfo.telephone : '',
  roleName: state => state.userInfo ? state.userInfo.roleName : '',
  enterpriseName: state => state.enterpriseInfo ? state.enterpriseInfo.enterpriseName : '',
  enterprisePerson: state => state.enterpriseInfo ? state.enterpriseInfo.enterprisePerson : '',
  enterpriseAddress: state => state.enterpriseInfo ? state.enterpriseInfo.enterpriseAddress : '',
  enterpriseEmail: state => state.enterpriseInfo ? state.enterpriseInfo.enterpriseEmail : '',
  isEnterpriseAuthen: state => state.enterpriseInfo ? state.enterpriseInfo.isEnterpriseAuthen === '1' : false,
  bussinessContactPhone: state => state.enterpriseInfo ? state.enterpriseInfo.bussinessContactPhone : '',
  bussinessContactPerson: state => state.enterpriseInfo ? state.enterpriseInfo.bussinessContactPerson : '',
  permissionList: state => state.permissionList
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_USER_INFO: (state, data) => {
    state.userInfo = data
  },
  SET_ENTERPRISE_INFO: (state, data) => {
    state.enterpriseInfo = data
  },
  SET_PERMISSION_LIST: (state, data) => {
    state.permissionList = data
  },
  CLEAR_INFO: (state) => {
    removeToken()
    state.token = null
    state.userInfo = null
    state.enterpriseInfo = null
    state.permissionList = []
  }
}

const actions = {
  // 登录
  login ({ commit, dispatch }, data) {
    const { username, password } = data
    return new Promise((resolve, reject) => {
      login({
        username: username.trim(),
        password
      }).then(async res => {
        if (res.success) {
          const { data } = res
          commit('SET_TOKEN', data.token)
          setToken(data.token)
          await dispatch('setUserInfo')
          resolve(res)
        } else {
          reject(res)
        }
      }).catch(error => {
        reject(error)
      })
    })
  },
  // 获取用户信息
  setUserInfo ({ commit }) {
    return new Promise((resolve, reject) => {
      getUserInfo().then(res => {
        const { data } = res
        if (!data) {
          console.error('用户信息获取失败！')
          reject(res)
        }
        const { userInfo, enterpriseInfoList, roleMenuPermission } = data
        commit('SET_USER_INFO', userInfo)
        roleMenuPermission && roleMenuPermission.permissionSet && commit('SET_PERMISSION_LIST', roleMenuPermission.permissionSet)
        if (enterpriseInfoList && enterpriseInfoList.length > 0) {
          commit('SET_ENTERPRISE_INFO', enterpriseInfoList[0])
        }
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },
  // 退出登录
  logout ({ commit }) {
    return new Promise((resolve) => {
      commit('CLEAR_INFO')
      resolve()
    })
  },

  // dynamically modify permissions
  // async changeRoles({ commit, dispatch }, role) {
  //   const token = role + '-token'

  //   commit('SET_TOKEN', token)
  //   setToken(token)

  //   const { roles } = await dispatch('getInfo')

  //   resetRouter()

  //   // generate accessible routes map based on roles
  //   const accessRoutes = await dispatch('permission/generateRoutes', roles, { root: true })
  //   // dynamically add accessible routes
  //   router.addRoutes(accessRoutes)

  //   // reset visited views and cached views
  //   dispatch('tagsView/delAllViews', null, { root: true })
  // }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
}
